import {Component, EventEmitter, forwardRef, Input, OnChanges, OnInit, Output, SimpleChanges} from '@angular/core';
import {_HttpClient} from '@delon/theme';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {DictService} from '@shared/service/dict.service';

@Component({
  selector: 'app-radio',
  template: `
    <nz-radio-group [(ngModel)]="model" [name]="name" (ngModelChange)="modelChange($event)">
      <ng-container *ngFor="let data of dictList">
        <label nz-radio [nzValue]="data.value">{{data.label}}</label>
      </ng-container>
    </nz-radio-group>
    `,
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => RadioComponent),
    multi: true
  }],
  styleUrls: ['./index.less']
})
export class RadioComponent implements OnInit, ControlValueAccessor, OnChanges {
  model: any;
  @Input() name;
  @Input() url;
  @Input() dictCode: string;
  @Input() dynamicDict = false;
  @Input() nzMode='default';
  @Input() disabled=false;


  @Output() ngModelChange = new EventEmitter();
  dictList;
  public onModelChange: any = () => { };
  public onModelTouched: any = () => { };
  writeValue(value: any) {
      this.model = value;
  }
  registerOnChange(fn: any): void {
    this.onModelChange = fn;
  }
  registerOnTouched(fn: any): void {
    this.onModelTouched = fn;
  }

  modelChange(value) {
    this.model = value;
    this.onModelChange(this.model); // 主要是要调用这个去重置绑定的model的值
    this.ngModelChange.emit(value);
  }

  constructor(public http: _HttpClient, private dictService: DictService) { }
  ngOnInit(): void {
    this.getDict();
  }
  ngOnChanges(changes: SimpleChanges) {
    if (!changes.dictCode.firstChange && this.dictCode != null && this.dynamicDict) {
      this.model = '';
      this.getDict();
    }
  }
  getDict() {
    const dict = this.dictCode.split(',');
    if (dict.length === 1) {
      this.dictService.getDict(dict[0]).subscribe((res) => (this.dictList = res));
    } else if (dict.length === 3) {
      this.dictService.getDictByTable(dict[0], dict[1], dict[2]).subscribe((res) => (this.dictList = res));
    }
  }
}
